package com.ns.dcjh.utils;


import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.webkit.ValueCallback;

import androidx.annotation.NonNull;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.ns.dcjh.listener.OnVideoPickCallback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

public class WebviewPickerUtils {
    private Context mContext;
    private ValueCallback<Uri[]> mFilePathCallback;
    private BitmapFactory.Options myoptions;

    private final String DCJH_FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dcjh";

    public WebviewPickerUtils(Context context) {
        mContext = context;
    }

    public WebviewPickerUtils(Context context, ValueCallback<Uri[]> filePathCallback) {
        mContext = context;
        mFilePathCallback = filePathCallback;
    }

    public void openImagePicker(Context context, int maxCount) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(maxCount)
                .isOriginalSkipCompress(true)
                .setSkipCropMimeType("image/jpeg", "image/png", "image/gif")
                .isAutomaticTitleRecyclerTop(true)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        //图片选择回调，主线程
                        if (mFilePathCallback == null) return;
                        ProgressDialog progressDialog = new ProgressDialog(mContext);
                        progressDialog.setMessage("图片正在处理中");
                        progressDialog.setCancelable(false);
                        progressDialog.show();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                ArrayList<Uri> fileList = new ArrayList<>();
                                for (LocalMedia item : result) {
                                    File imageFile = new File(item.getRealPath());
                                    fileList.add(Uri.fromFile(convertHeicToJpg(mContext, imageFile)));
                                }
                                mFilePathCallback.onReceiveValue(fileList.toArray(new Uri[0]));
                                progressDialog.dismiss();
                            }
                        }).start();
                    }

                    @Override
                    public void onCancel() {
                        if (mFilePathCallback == null) return;
                        mFilePathCallback.onReceiveValue(null);
                    }
                });
    }

    public static File convertHeicToJpg(@NonNull Context context, @NonNull File inputFile) {
        if (!isHeicFile(inputFile)) {
            return inputFile;
        }

        try {
            Uri uri = Uri.fromFile(inputFile);
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return null;
            }

            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();

            if (bitmap == null) {
                return null;
            }

            File outputDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (outputDir == null) {
                return null;
            }

            String outputFileName = System.currentTimeMillis() + ".jpg";
            File outputFile = new File(outputDir, outputFileName);

            FileOutputStream outputStream = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            bitmap.recycle();

            return outputFile;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static boolean isHeicFile(@NonNull File file) {
        String fileName = file.getName().toLowerCase();
        return fileName.endsWith(".heic") || fileName.endsWith(".heif");
    }

    public static Uri convertToImage(Context context, Uri imageUri) {
        Uri fileUri = null;
        try {
            ContentResolver contentResolver = context.getContentResolver();
            InputStream inputStream = contentResolver.openInputStream(imageUri);

            // Get rotation information from the image
            int rotation = getRotationFromUri(context, imageUri);

            // Decode image with rotation information
            Bitmap bitmap = decodeBitmapWithRotation(inputStream, rotation);

            if (bitmap != null) {
                String[] split = imageUri.getPath().split("/");
                if ("PNG".equals(detectImageFormat(context, imageUri))) {
                    String pngFilePath = context.getCacheDir().getAbsolutePath() + "/" + split[split.length - 1] + "_converted_image.png";
                    File pngFile = new File(pngFilePath);
                    OutputStream outputStream = new FileOutputStream(pngFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 80, outputStream);
                    outputStream.close();
                    fileUri = Uri.fromFile(pngFile);
                } else {
                    String jpgFilePath = context.getCacheDir().getAbsolutePath() + "/" + split[split.length - 1] + "_converted_image.jpg";
                    File jpgFile = new File(jpgFilePath);

                    OutputStream outputStream = new FileOutputStream(jpgFile);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outputStream);
                    outputStream.close();
                    fileUri = Uri.fromFile(jpgFile);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileUri;
    }

    public static String detectImageFormat(Context context, Uri uri) {
        try {
            ContentResolver resolver = context.getContentResolver();

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                // Android 10 and above, use SAF (Storage Access Framework) methods
                String mimeType = resolver.getType(uri);
                if (mimeType != null) {
                    if (mimeType.equals("image/jpeg")) {
                        return "JPEG";
                    } else if (mimeType.equals("image/png")) {
                        return "PNG";
                    }
                }
            } else {
                // For older versions, use cursor query
                String[] projection = {MediaStore.Images.Media.DATA};
                Cursor cursor = resolver.query(uri, projection, null, null, null);
                if (cursor != null) {
                    try {
                        if (cursor.moveToFirst()) {
                            String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeFile(filePath, options);
                            String formatName = options.outMimeType;
                            if (formatName.equals("image/jpeg")) {
                                return "JPEG";
                            } else if (formatName.equals("image/png")) {
                                return "PNG";
                            }
                        }
                    } finally {
                        cursor.close();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Unknown";
    }

    private static int getRotationFromUri(Context context, Uri imageUri) {
        String[] projection = {MediaStore.Images.ImageColumns.ORIENTATION};
        Cursor cursor = context.getContentResolver().query(imageUri, projection, null, null, null);
        int rotation = 0;

        if (cursor != null) {
            if (cursor.getColumnCount() > 0 && cursor.moveToFirst()) {
                rotation = cursor.getInt(0);
            }
            cursor.close();
        }

        return rotation;
    }

    private static Bitmap decodeBitmapWithRotation(InputStream inputStream, int rotation) throws IOException {
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        if (bitmap == null) {
            return null;
        }

        if (rotation != 0) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotation);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
            bitmap.recycle(); // Recycle original bitmap
            return rotatedBitmap;
        }

        return bitmap;
    }

    public void openVideoPicker(Context context) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofVideo())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        //图片选择回调，主线程
                        if (mFilePathCallback == null) return;
                        ArrayList<Uri> fileList = new ArrayList<>();
                        for (LocalMedia item : result) {
                            File imageFile = new File(item.getRealPath());
                            fileList.add(Uri.fromFile(imageFile));
                        }
                        mFilePathCallback.onReceiveValue(fileList.toArray(new Uri[0]));
                    }

                    @Override
                    public void onCancel() {
                        if (mFilePathCallback == null) return;
                        mFilePathCallback.onReceiveValue(null);
                    }
                });
    }

    public void openVideoPickerNew(Context context, OnVideoPickCallback onCallback) {
        PictureSelector.create(context)
                .openGallery(SelectMimeType.ofVideo())
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (result.isEmpty()) return;
                        String path = result.get(0).getRealPath();
                        if (path == null) return;
                        double fileSize = FileSizeUtil.getFileOrFilesSize(path, 3);
                        if (fileSize > 800) {
                            onCallback.onPickFailCallback("选取视频大于800M，请重新选择");
                            return;
                        }
                        onCallback.onPickCallback(new File(path));
                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }

    private String getVideoFileOutPath() {
        File videoFir = new File(DCJH_FILE_PATH, "video");
        if (!videoFir.exists()) {
            videoFir.mkdirs();
        }

        return new File(videoFir.getPath() + File.separator + "dcjh_" + System.currentTimeMillis() + ".mp4").getAbsolutePath();
    }

}
